﻿package org.minuframework.kdniao.logistics;

import java.util.HashMap;
import java.util.Map;
import org.minuframework.encrypt.UrlUtils;
import org.minuframework.json.GsonUtils;
import org.minuframework.kdniao.logistics.encrypt.KdniaoU;
import org.minuframework.kdniao.logistics.entity.KdniaoLogistics;
import org.minuframework.net.HttpUtils;
import org.minuframework.net.RequestMethod;

/**
 * 快递鸟物流轨迹即时查询接口
 * 
 * @技术QQ群: 456320272
 * @see: http://www.kdniao.com/YundanChaxunAPI.aspx
 * @copyright: 深圳市快金数据技术服务有限公司 DEMO中的电商ID与私钥仅限测试使用，正式环境请单独注册账号 单日超过500单查询量，建议接入我方物流轨迹订阅推送接口
 *             ID和Key请到官网申请：http://www.kdniao.com/ServiceApply.aspx
 */

public class KdniaoTrackQueryAPI {

    /**
     * 请求url
     */
    private static final String ReqURL = "http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx";

    private static final KdniaoLogisticsConfigurer KDNIAO_LOGISTICS_CONFIGURER =
            new KdniaoLogisticsConfigurer();

    /**
     * Json方式 查询订单物流轨迹
     * 
     * @throws Exception
     */
    public String getOrderTracesByJson(String expCode, String expNo) throws Exception {
        String requestData =
                "{'OrderCode':'','ShipperCode':'" + expCode + "','LogisticCode':'" + expNo + "'}";

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("RequestData", UrlUtils.urlEncoder(requestData, "UTF-8"));
        params.put("EBusinessID", KDNIAO_LOGISTICS_CONFIGURER.getEBusinessID());
        params.put("RequestType", "1002");
        String dataSign =
                KdniaoU.encrypt(requestData, KDNIAO_LOGISTICS_CONFIGURER.getAppKey(), "UTF-8");
        params.put("DataSign", UrlUtils.urlEncoder(dataSign, "UTF-8"));
        params.put("DataType", "2");

        String result = HttpUtils.sendHttp(ReqURL, params, RequestMethod.POST);

        // 根据公司业务处理返回的信息......

        return result;
    }

    /**
     * 查询订单物流轨迹
     * 
     * @param expCode 快递公司编码
     * @param expNo 物流运单号
     * @return 订单物流轨迹信息 KdniaoLogistics
     * @throws Exception
     */
    public KdniaoLogistics getOrderTraces(String expCode, String expNo) throws Exception {
        String jsonString = getOrderTracesByJson(expCode, expNo);
        KdniaoLogistics kdniaoLogistics =
                GsonUtils.fromGSONString(jsonString, KdniaoLogistics.class);
        return kdniaoLogistics;
    }

}
